package javase.javase02.networkprograming;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author: Gan
 * @date 2021/4/23 0023 22:23
 * @description:接收端 3.实现多线程聊天(用 UDP TCP 都可以)
 **/
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int Port;
    private String msgFrom;

    public TalkReceive(int Port, String msgFrom) {
        this.Port = Port;
        this.msgFrom = msgFrom;
        try {
            //DatagramSocket(int port)
            //创建数据报套接字并将其绑定到本地主机上的指定端口
            socket = new DatagramSocket(Port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                byte[] buffer = new byte[1024];
                //封装成数据报包
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(packet);
                //把收到的数据报包解析出来，并转换成字符串
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                //打印出消息来源和其发送的消息
                System.out.println(msgFrom + ": " + receiveData);
                //约定以bye结束接收消息
                if (receiveData.equals("bye"))
                    break;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();

    }

}
